import 'package:async/async.dart';
import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/banner_controller.dart';
import 'package:efood_multivendor/controller/campaign_controller.dart';
import 'package:efood_multivendor/controller/category_controller.dart';
import 'package:efood_multivendor/controller/filter_controller.dart';
import 'package:efood_multivendor/controller/location_controller.dart';
import 'package:efood_multivendor/controller/notification_controller.dart';
import 'package:efood_multivendor/controller/product_controller.dart';
import 'package:efood_multivendor/controller/restaurant_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/controller/user_controller.dart';
import 'package:efood_multivendor/data/model/response/config_model.dart';
import 'package:efood_multivendor/helper/date_converter.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/screens/dashboard/widget/location_dialog.dart';
import 'package:efood_multivendor/view/screens/home/widget/banner_view.dart';
import 'package:efood_multivendor/view/screens/home/widget/category_view.dart';
import 'package:efood_multivendor/view/screens/home/widget/item_campaign_view.dart';
import 'package:efood_multivendor/view/screens/home/widget/popular_food_view.dart';
import 'package:efood_multivendor/view/screens/home/widget/popular_restaurant_view.dart';
import 'package:efood_multivendor/view/screens/home/widget/restaurant_view.dart';
import 'package:efood_multivendor/view/screens/search/widget/filter_widget.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:get/get.dart';

class HomeScreen extends StatefulWidget {
  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  late int addressLength;

  @override
  void initState() {
    super.initState();
    addressLength = Get.find<LocationController>().addressList.length;
  }

  Future<void> loadData(bool reload) async {
    if (Get.find<AuthController>().isLoggedIn()) {
      await Get.find<BannerController>().getBannerList(reload);
      await Get.find<CategoryController>().getCategoryList(reload);

      await Get.find<CampaignController>().getItemCampaignList(reload,
          filter: Get.find<SplashController>()
              .configModel!
              .defaultCampaignFilter
              .toString());

      await Get.find<RestaurantController>().getRestaurantList('1', reload);

      await Get.find<NotificationController>().getNotificationList(reload);
      Get.find<FilterController>().setPrice(
          Get.find<SplashController>()
              .configModel
              ?.minimumProductPrice
              ?.toDouble(),
          Get.find<SplashController>()
              .configModel
              ?.maximumProductPrice
              ?.toDouble());
    }
  }

  @override
  Widget build(BuildContext context) {
    final ScrollController _scrollController = ScrollController();

    // loadLocation();
    ConfigModel? _configModel = Get.find<SplashController>().configModel;
    bool isLogedin = false;
    if (Get.find<AuthController>().isLoggedIn()) {
      isLogedin = true;
    }

    return WillPopScope(
      onWillPop: () async {
        int i = 1;
        if (i == 1) {
          SystemNavigator.pop();
          return false;
        } else {
          return false;
        }
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        body: SafeArea(
          bottom: false,
          child: RefreshIndicator(
            color: Theme.of(context).colorScheme.secondary,
            onRefresh: () async {
              await Get.find<BannerController>().getBannerList(true);
              await Get.find<CategoryController>().getCategoryList(true);

              await Get.find<CampaignController>().getItemCampaignList(true,
                  filter: Get.find<SplashController>()
                      .configModel!
                      .defaultCampaignFilter
                      .toString());

              await Get.find<RestaurantController>()
                  .getRestaurantList('1', true);
              if (Get.find<AuthController>().isLoggedIn()) {
                await Get.find<UserController>().getUserInfo();
              }
            },
            child: CustomScrollView(
              controller: _scrollController,
              physics: ClampingScrollPhysics(),
              slivers: [
                SliverAppBar(
                  floating: true,
                  elevation: 0,
                  automaticallyImplyLeading: false,
                  backgroundColor: Colors.white,
                  title: Center(
                      child: Container(
                    width: Dimensions.WEB_MAX_WIDTH,
                    height: 50,
                    color: Colors.white,
                    child: Row(children: [
                      Expanded(
                          child: InkWell(
                        onTap: () async {
                          if (isLogedin &&
                              Get.find<SplashController>()
                                      .configModel
                                      ?.isAddressChangeAllowed ==
                                  true) {
                            if (addressLength != 0) {
                              if (addressLength > 0) {
                                Get.dialog(
                                  LocationDialog(
                                    isSavedLocationEmpty: false,
                                    isSavedLocationFound: true,
                                    locationInput: false,
                                  ),
                                );
                              }
                            } else {
                              if (addressLength == 0) {
                                Get.dialog(LocationDialog(
                                    isSavedLocationEmpty: true,
                                    isSavedLocationFound: false,
                                    locationInput: false,
                                    fromEmptyHome: true));
                              }
                            }
                          }
                        },
                        child: Padding(
                          padding: EdgeInsets.symmetric(
                            vertical: Dimensions.PADDING_SIZE_SMALL,
                            horizontal: 0,
                          ),
                          child: GetBuilder<LocationController>(
                              builder: (locationController) {
                            return locationController.getUserAddress() == null
                                ? SizedBox()
                                : locationController
                                            .getUserAddress()
                                            ?.addressType !=
                                        null
                                    ? Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        children: [
                                          Icon(
                                            locationController
                                                        .getUserAddress()
                                                        ?.addressType ==
                                                    'home'
                                                ? Icons.home_filled
                                                : locationController
                                                            .getUserAddress()
                                                            ?.addressType ==
                                                        'office'
                                                    ? Icons.work
                                                    : FeatherIcons.mapPin,
                                            size: 20,
                                            color: Theme.of(context)
                                                .textTheme
                                                .bodyMedium
                                                ?.color,
                                          ),
                                          SizedBox(width: 10),
                                          Flexible(
                                            child: Text(
                                              locationController
                                                      .getUserAddress()
                                                      ?.address ??
                                                  '',
                                              style: sfRegular.copyWith(
                                                color: Theme.of(context)
                                                    .textTheme
                                                    .bodyMedium
                                                    ?.color,
                                                fontSize:
                                                    Dimensions.fontSizeSmall,
                                              ),
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                          Get.find<SplashController>()
                                                      .configModel
                                                      ?.isAddressChangeAllowed ==
                                                  true
                                              ? Icon(Icons.arrow_drop_down,
                                                  color: Theme.of(context)
                                                      .textTheme
                                                      .bodyMedium
                                                      ?.color)
                                              : SizedBox()
                                        ],
                                      )
                                    : SizedBox();
                          }),
                        ),
                      )),
                      InkWell(
                        child: GetBuilder<NotificationController>(
                            builder: (notificationController) {
                          bool _hasNewNotification = false;
                          if (notificationController.notificationList != null) {
                            _hasNewNotification = notificationController
                                    .notificationList?.length !=
                                notificationController
                                    .getSeenNotificationCount();
                          }
                          return Stack(children: [
                            Icon(Icons.notifications,
                                size: 25,
                                color: Theme.of(context)
                                    .textTheme
                                    .bodyMedium
                                    ?.color),
                            _hasNewNotification
                                ? Positioned(
                                    top: 0,
                                    right: 0,
                                    child: Container(
                                      height: 10,
                                      width: 10,
                                      decoration: BoxDecoration(
                                        color: Theme.of(context)
                                            .colorScheme
                                            .secondary,
                                        shape: BoxShape.circle,
                                        border: Border.all(
                                            width: 1,
                                            color: Theme.of(context).cardColor),
                                      ),
                                    ))
                                : SizedBox(),
                          ]);
                        }),
                        onTap: () =>
                            Get.toNamed(RouteHelper.getNotificationRoute()),
                      ),
                    ]),
                  )),
                ),
                SliverPersistentHeader(
                  pinned: true,
                  delegate: SliverDelegate(
                      child: Center(
                          child: Container(
                    height: 50,
                    width: Dimensions.WEB_MAX_WIDTH,
                    color: Colors.white,
                    child: InkWell(
                      onTap: () async {
                        Get.toNamed(RouteHelper.getSearchRoute());
                        await FirebaseAnalytics.instance
                            .logEvent(name: 'search_bar_clicked', parameters: {
                          'timestamp': DateConverter.getCurrentTimeInGmtPlus3()
                              .toString()
                        });
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: Dimensions.PADDING_SIZE_SMALL * 2),
                        decoration: BoxDecoration(
                          color: Colors.grey[200],
                          borderRadius:
                              BorderRadius.circular(Dimensions.RADIUS_SMALL),
                        ),
                        child: Row(children: [
                          Icon(FeatherIcons.search,
                              size: 25, color: Colors.grey),
                          SizedBox(width: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                          Expanded(
                              child: Text('search_food_or_restaurant'.tr,
                                  style: sfRegular.copyWith(
                                    fontSize: Dimensions.fontSizeSmall,
                                    color: Theme.of(context).hintColor,
                                  ))),
                        ]),
                      ),
                    ),
                  ))),
                ),
                SliverToBoxAdapter(
                  child: Center(
                      child: SizedBox(
                          width: Dimensions.WEB_MAX_WIDTH,
                          child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                GetBuilder<BannerController>(
                                    builder: (bannerController) {
                                  return bannerController
                                          .bannerImageList.isEmpty
                                      ? BannerView(
                                          bannerController: bannerController)
                                      : bannerController
                                                  .bannerImageList.length ==
                                              0
                                          ? SizedBox()
                                          : BannerView(
                                              bannerController:
                                                  bannerController);
                                }),
                                SizedBox(
                                    height:
                                        Dimensions.PADDING_SIZE_EXTRA_SMALL *
                                            2),
                                GetBuilder<CategoryController>(
                                    builder: (categoryController) {
                                  return categoryController.categoryList == null
                                      ? CategoryView(
                                          categoryController:
                                              categoryController)
                                      : categoryController
                                                  .categoryList?.isNotEmpty !=
                                              true
                                          ? SizedBox()
                                          : CategoryView(
                                              categoryController:
                                                  categoryController);
                                }),
                                _configModel?.popularRestaurant == 1
                                    ? GetBuilder<RestaurantController>(
                                        builder: (restController) {
                                        return restController
                                                    .popularRestaurantList ==
                                                null
                                            ? PopularRestaurantView(
                                                restController: restController,
                                                isPopular: true)
                                            : restController
                                                        .popularRestaurantList
                                                        ?.isNotEmpty !=
                                                    true
                                                ? SizedBox()
                                                : PopularRestaurantView(
                                                    restController:
                                                        restController,
                                                    isPopular: true);
                                      })
                                    : SizedBox(),
                                GetBuilder<CampaignController>(
                                    builder: (campaignController) {
                                  return campaignController
                                          .itemCampaignList.isEmpty
                                      ? ItemCampaignView(
                                          campaignController:
                                              campaignController)
                                      : campaignController
                                                  .itemCampaignList.length ==
                                              0
                                          ? SizedBox()
                                          : ItemCampaignView(
                                              campaignController:
                                                  campaignController);
                                }),
                                _configModel?.popularFood == 1
                                    ? GetBuilder<ProductController>(
                                        builder: (productController) {
                                        return productController
                                                    .popularProductList ==
                                                null
                                            ? PopularFoodView(
                                                productController:
                                                    productController,
                                                isPopular: true)
                                            : productController
                                                        .popularProductList
                                                        ?.isNotEmpty !=
                                                    true
                                                ? SizedBox()
                                                : PopularFoodView(
                                                    productController:
                                                        productController,
                                                    isPopular: true);
                                      })
                                    : SizedBox(),
                                _configModel?.newRestaurant == 1
                                    ? GetBuilder<RestaurantController>(
                                        builder: (restController) {
                                        return restController
                                                    .latestRestaurantList ==
                                                null
                                            ? PopularRestaurantView(
                                                restController: restController,
                                                isPopular: false)
                                            : restController
                                                        .latestRestaurantList
                                                        ?.isNotEmpty !=
                                                    true
                                                ? SizedBox()
                                                : PopularRestaurantView(
                                                    restController:
                                                        restController,
                                                    isPopular: false);
                                      })
                                    : SizedBox(),
                                _configModel?.mostReviewedFoods == 1
                                    ? GetBuilder<ProductController>(
                                        builder: (productController) {
                                        return productController
                                                    .reviewedProductList ==
                                                null
                                            ? PopularFoodView(
                                                productController:
                                                    productController,
                                                isPopular: false)
                                            : productController
                                                        .reviewedProductList
                                                        ?.isNotEmpty !=
                                                    true
                                                ? SizedBox()
                                                : PopularFoodView(
                                                    productController:
                                                        productController,
                                                    isPopular: false);
                                      })
                                    : SizedBox(),
                                Padding(
                                  padding: EdgeInsets.fromLTRB(10, 15, 0, 5),
                                  child: GetBuilder<RestaurantController>(
                                      builder: (restaurantController) {
                                    return Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Row(children: [
                                          Expanded(
                                              flex: 6,
                                              child: Text('all_restaurants'.tr,
                                                  style: sfMedium.copyWith(
                                                      fontWeight:
                                                          FontWeight.bold,
                                                      fontSize: Dimensions
                                                              .fontSizeLarge *
                                                          1.1))),
                                          restaurantController.restaurantList !=
                                                  null
                                              ? Wrap(children: [
                                                  Padding(
                                                    padding:
                                                        const EdgeInsets.only(
                                                            right: 8.0),
                                                    child: GestureDetector(
                                                        onTap: () {
                                                          Get.bottomSheet(
                                                            FilterWidget(
                                                                maxValue: 1000,
                                                                isRestaurant:
                                                                    true),
                                                            isScrollControlled:
                                                                true,
                                                            shape: const RoundedRectangleBorder(
                                                                borderRadius:
                                                                    BorderRadius
                                                                        .vertical(
                                                                            top:
                                                                                Radius.circular(25.0))),
                                                          );
                                                        },
                                                        child: Container(
                                                          padding:
                                                              EdgeInsets.all(3),
                                                          decoration: BoxDecoration(
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .circular(
                                                                          5),
                                                              border: Border.all(
                                                                  color: Theme.of(
                                                                          context)
                                                                      .colorScheme
                                                                      .secondary)),
                                                          child: Center(
                                                            child: Text(
                                                              'filter'.tr,
                                                              style: sfMedium.copyWith(
                                                                  color: Theme.of(
                                                                          context)
                                                                      .colorScheme
                                                                      .secondary,
                                                                  fontWeight:
                                                                      FontWeight
                                                                          .bold,
                                                                  fontSize:
                                                                      Dimensions
                                                                              .fontSizeLarge *
                                                                          0.87),
                                                            ),
                                                          ),
                                                        )),
                                                  ),
                                                ])
                                              : SizedBox()
                                        ]),
                                      ],
                                    );
                                  }),
                                ),
                                RestaurantView(
                                    scrollController: _scrollController),
                              ]))),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class SliverDelegate extends SliverPersistentHeaderDelegate {
  Widget child;

  SliverDelegate({required this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }

  @override
  double get maxExtent => 50;

  @override
  double get minExtent => 50;

  @override
  bool shouldRebuild(SliverDelegate oldDelegate) {
    return oldDelegate.maxExtent != 50 ||
        oldDelegate.minExtent != 50 ||
        child != oldDelegate.child;
  }
}
